// 视差滚动指令
export const vParallax = {
  mounted(el, binding) {
    // 获取配置参数
    const config = binding.value || {}
    const {
      speed = 0.15,        // 滚动速度
      direction = 'up'     // 方向：up, down
    } = config

    const updateParallax = () => {
      const rect = el.getBoundingClientRect()
      const scrollTop = window.scrollY
      const windowHeight = window.innerHeight
      
      // 计算元素相对于视口的位置
      const elementTop = rect.top
      const elementHeight = rect.height
      
      // 计算元素在视口中的可见范围
      const visibleTop = Math.max(0, -elementTop)
      const visibleBottom = Math.min(windowHeight, -elementTop + elementHeight)
      const visibleHeight = visibleBottom - visibleTop
      
      // 只有当元素在视口中可见时才应用视差效果
      if (visibleHeight > 0) {
        // 计算元素在视口中的位置百分比 (0 到 1)
        const viewportPosition = (elementTop + elementHeight / 2) / (windowHeight + elementHeight)
        
        // 计算视差位移，并限制最大位移范围
        const maxOffset = elementHeight * 0.3 // 限制最大位移为元素高度的30%
        const offset = direction === 'up'
          ? Math.min(maxOffset, scrollTop * speed)
          : Math.max(-maxOffset, -scrollTop * speed)

        // 应用变换
        el.style.transform = `translate3d(0, ${offset}px, 0)`
        el.style.willChange = 'transform'
      }
    }

    // 使用 requestAnimationFrame 优化性能
    let ticking = false
    const requestTick = () => {
      if (!ticking) {
        requestAnimationFrame(() => {
          updateParallax()
          ticking = false
        })
        ticking = true
      }
    }

    // 添加滚动事件监听器
    window.addEventListener('scroll', requestTick, { passive: true })
    window.addEventListener('resize', requestTick)

    // 初始化位置
    requestTick()

    // 存储清理函数
    el._parallaxCleanup = () => {
      window.removeEventListener('scroll', requestTick)
      window.removeEventListener('resize', requestTick)
    }
  },
  
  unmounted(el) {
    // 清理事件监听器
    if (el._parallaxCleanup) {
      el._parallaxCleanup()
    }
  }
}
